import React, { Component } from 'react'
import { connect } from 'dva';
import { Table, Divider, Modal, message, Button } from 'antd';
import SearchBuild from './SearchBuild';

export interface Props {
  dispatch?: Function,
  selectedDevice?: Function,
  isSearchData?: Function,
  children?: React.ReactNode,
  loading?: boolean,
  isSearchReset?: boolean,
  buildList?: {
    data: Array<any>,
    dataCnt: number
  },
  buttons?: Array<any>,
  dict?: object,
  isCancel?: any,
  deviceSelectedData?: Array<any>
}
const ONE_PAGE_SIZE = 5;

const bbType = {
  '0': '无',
  '1': '有'
};

@connect(({ unit_task_rules, loading }) => ({
  buildList: unit_task_rules.buildList,
  loading: loading.effects['unit_task_rules/queryBuildPage']
}))
class FormBuildList extends Component<Props, any> {
  constructor(props) {
    super(props);
    this.state = {
      current: 1,
      index: 1,
      indexList: [],
      selectedRowKeys: [],
      rowData: [],
      selectedObj: {},
      searchData: {},
      deviceRules: {
        data: [],
        dataCnt: 0
      },
      visible: false,
      isSearch: false,
      isSearchReset: false,
      isChangePageNum: false
    };
    this.initCurrent = this.initCurrent.bind(this);
  }

  componentWillMount() {
    this.queryData();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.deviceSelectedData !== this.props.deviceSelectedData) {
      let tj_obj = {};
      let pageObj = {};
      let len = nextProps.deviceSelectedData.length;
      let data = nextProps.deviceSelectedData;
      for (let i = 0; i < len; i++) {
        if (!tj_obj[data[i]['pageNum']]) {
          pageObj['pageNum' + data[i]['pageNum']] = [data[i]];
          tj_obj[data[i]['pageNum']] = `${i}`;
        } else {
          pageObj['pageNum' + data[i]['pageNum']] = [data[i], ...pageObj['pageNum' + data[i]['pageNum']]];
        }
      }
      let selectedRowKeys = [];
      if (Array.isArray(pageObj['pageNum' + this.state.current])) {
        pageObj['pageNum' + this.state.current].forEach(item => {
          selectedRowKeys.push(item.key);
        });
      }
      this.setState({
        selectedObj: pageObj,
        selectedRowKeys,
        rowData: []
      })
    }
    if (nextProps.isSearchReset !== this.props.isSearchReset) {
      this.setState({
        isSearchReset: !this.state.isSearchReset
      })
    }
  }

  queryData(offset = 1, size = ONE_PAGE_SIZE) {
    const { dispatch } = this.props;
    dispatch({
      type: 'unit_task_rules/queryBuildPage',
      payload: {
        pageNum: offset,
        pageSize: size,
      },
    });
  }

  initCurrent() {
    this.setState({
      current: 1,
      index: 1,
      indexList: [],
      isChangePageNum: false,
      selectedRowKeys: [],
      rowData: [],
      selectedObj: {}
    });
    this.props.isSearchData();
  }

  onSelectChange = (selectedRowKeys, rowData) => {
    this.setState({
      selectedRowKeys,
      rowData
    });
    this.props.selectedDevice(rowData, this.state.selectedObj, this.state.indexList, this.state.isChangePageNum);
  };

  render() {
    const { buildList = { data: [], dataCnt: 0 } } = this.props;
    const { data = [], dataCnt } = buildList;
    const ans = data && Array.isArray(data) ? data.map((item) => ({
      key: item.id,
      pageNum: this.state.current,
      buildName: item.buildName,
      buildAddress: item.buildAddress,
      floorName: item.floorName,
      floorType: item.floorType,
      floorTypeName: item.floorTypeName,
      existsReportTemplate: bbType[item.existsReportTemplate],
      templateStatus: item.existsReportTemplate,
      createTime: item.createTime
    })
    ) : [];
    const pagination = {
      total: dataCnt,
      current: this.state.current,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      pageSize: ONE_PAGE_SIZE,
      onChange: (current) => {
        if (this.state.rowData.length > 0) {
          this.state.indexList.push(this.state.index);
          this.state.selectedObj['pageNum' + this.state.index] = JSON.parse(JSON.stringify(this.state.rowData));
        }
        let selectedRowKeys = [];
        if (this.state.selectedObj['pageNum' + current]) {
          this.state.selectedObj['pageNum' + current].forEach(item => {
            selectedRowKeys.push(item.key);
          });
        }
        this.setState({
          current,
          index: current,
          indexList: this.state.indexList,
          isChangePageNum: true,
          selectedRowKeys: selectedRowKeys,
          rowData: []
        });
        this.queryData(current)
      },
    };
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      'type': 'checkbox',
      onChange: this.onSelectChange,
    };
    const columns = [
      {
        title: '楼层名称',
        dataIndex: 'floorName',
      }, {
        title: '楼宇名称',
        dataIndex: 'buildName',
      }, {
        title: '楼宇地址',
        dataIndex: 'buildAddress',
      }, {
        title: '楼层类型',
        dataIndex: 'floorTypeName',
      }, {
        title: '是否存在报表模板',
        dataIndex: 'existsReportTemplate'
      }, {
        title: '创建时间',
        dataIndex: 'createTime'
      }];
    return (
      <div>
        <SearchBuild current={this.state.current} initCurrent={this.initCurrent} isSearchReset={this.state.isSearchReset} />
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          bordered
          loading={this.props.loading}
          rowSelection={rowSelection}
        />
      </div>
    );
  }
}

export default FormBuildList;
